class Login {
    constructor() {
        this.form = document.querySelector('.login-form');
        this.username = document.querySelector('#username');
        this.password = document.querySelector('#password');
        
        this.init();
    }

    init() {
        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSubmit();
        });
    }

    // 表单验证
    validate() {
        // 用户名验证
        if (!this.username.value) {
            alert('请输入用户名');
            return false;
        }
        if (!/^[a-z0-9]\w{3,11}$/.test(this.username.value)) {
            alert('用户名格式不正确');
            return false;
        }

        // 密码验证
        if (!this.password.value) {
            alert('请输入密码');
            return false;
        }
        if (!/\w{6,12}/.test(this.password.value)) {
            alert('密码格式不正确');
            return false;
        }

        return true;
    }

    // 处理表单提交
    async handleSubmit() {
        if (!this.validate()) return;

        try {
            const response = await fetch('http://localhost:8888/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    username: this.username.value,
                    password: this.password.value
                })
            });

            const data = await response.json();
            
            if (data.code === 1) {
                // 保存登录信息
                localStorage.setItem('token', data.token);
                localStorage.setItem('userInfo', JSON.stringify(data.user));
                
                alert('登录成功！');
                window.location.href = 'index.html';
            } else {
                alert(data.message || '登录失败，请检查用户名和密码');
            }
        } catch (error) {
            alert('登录失败，请检查网络连接');
            console.error('登录错误：', error);
        }
    }
}

// 初始化登录功能
document.addEventListener('DOMContentLoaded', () => {
    new Login();
}); 